package com.ruoyi.web.controller.modules;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.modules.domain.Unit;
import com.ruoyi.modules.service.UnitService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;

import static com.ruoyi.common.utils.graphics.GraphicsUtils.startGraphics2D;


/**
 * 签章机构信息
 *
 * @author tlgen
 */
@RestController
@RequestMapping("/county/unit/data")
public class UnitController extends BaseController
{
    @Autowired
    private UnitService unitService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询所有签章机构信息
     * @param unit 签章机构对象
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo list(Unit unit)
    {
        startPage();
        List<Unit> list = unitService.selectUnitList(unit);
        return getDataTable(list);
    }

    /**
     * 导出签章机构信息
     * @param unit 签章机构
     * @return
     */
    @Log(title = "导出签章机构信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Unit unit)
    {
        List<Unit> list = unitService.selectUnitList(unit);
        ExcelUtil<Unit> util = new ExcelUtil<Unit>(Unit.class);
        return util.exportExcel(list, "签章机构数据");
    }

    /**
     * 根据签章机构编号unitId查询签章机构信息
     * @param unitId 签章机构编号
     * @return
     */
    @ApiOperation("根据ID查询签章机构信息")
    @GetMapping(value = "/{unitId}")
    public AjaxResult getInfo(@PathVariable Long unitId)
    {
        return AjaxResult.success(unitService.selectUnitById(unitId));
    }

    /**
     * 通过当前user_id获取dept_name
     * 业务dept_name 与 unitName相同名称
     * 再签章机构名称获取机构信息
     * 得到我的电子印章图片
     */
    /**
     * 根据签章机构名称获取机构信息
     * @return
     */
    @GetMapping(value = "/name/getSignatureByUnitName")
    public AjaxResult getSignatureByUnitName()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (!StringUtils.isNull(loginUser)) {
            SysUser user = userService.selectUserById(loginUser.getUser().getUserId());
            List<Unit> unitList = unitService.selectUnitByUnitName(user.getDept().getDeptName());

            AjaxResult ajax = AjaxResult.success();
            ajax.put("msg", "获取成功!");
            ajax.put("unitList", unitList);
            return ajax;
        } else {
            return AjaxResult.error("获取失败!");
        }
    }

    /**
     * 新增签章机构信息
     * @param unit 签章对象
     * @return
     */
    @Log(title = "新增签章机构信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody Unit unit)
    {
        unit.setCreateBy(SecurityUtils.getUsername());
        return toAjax(unitService.insertUnit(unit));
    }

    /**
     * 修改签章机构信息
     * @param unit 签章对象
     * @return
     */
    @Log(title = "修改签章机构信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Unit unit)
    {
        unit.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(unitService.updateUnit(unit));
    }

    /**
     * 删除签章机构信息
     * @param unitIds 签章编号, 可批量
     * @return
     */
    @Log(title = "删除签章机构信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{unitIds}")
    public AjaxResult remove(@PathVariable Long[] unitIds)
    {
        return toAjax(unitService.deleteUnitByIds(unitIds));
    }

    /**
     * 生成电子签章
     * @param unitId 签章编号
     * @param message 签章描述
     * @param centerName 机构名称
     * @param year 年份
     * @return
     */
    @Log(title = "生成电子签章", businessType = BusinessType.UPDATE)
    @PutMapping("/generateGraphic")
    public AjaxResult generateGraphic(@RequestParam("unitId") Long unitId,
                                      @RequestParam("message") String message, @RequestParam("centerName") String centerName, @RequestParam("year") String year) {

        Unit Unit = unitService.selectUnitById(unitId);

        BufferedImage image = startGraphics2D(message, centerName, year);
        try {
            // 生成的签章保存在 E:/images/ 下
            String filePath = "E:\\images\\"+new Date().getTime()+".png";
            ImageIO.write(image, "png", new File(filePath));

            // 将java.io.File转为MultipartFile
            File newFile = new File(filePath);
            FileInputStream inputStream = new FileInputStream(newFile);
            MultipartFile multipartFile = new MockMultipartFile("file", newFile.getName(), "text/plain", IOUtils.toByteArray(inputStream));

            System.out.println(multipartFile);

            // 上传
            String imagFilePath = FileUploadUtils.upload(RuoYiConfig.getUploadImageFile(), multipartFile);
            System.out.println(imagFilePath);

            if (unitService.updateUnitUploadImage(unitId, imagFilePath))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imagFilePath", imagFilePath);
                // 更新
                Unit.setUnitSignature(imagFilePath);
                unitService.updateUnit(Unit);
                return ajax;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

}
